package net.wanho.ums.dao.impl;

import net.wanho.ums.dao.UserDao;
import net.wanho.ums.entity.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Author：汤小洋
 * Date：2023-12-08 14:08
 * Description：<描述>
 */
public class UserDaoImpl implements UserDao {

    @Override
    public void insert(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 1.加载驱动类
            Class.forName("com.mysql.jdbc.Driver");
            // 2.获取连接
             conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ums?useUnicode=true&characterEncoding=utf8", "root", "root");
            // 3.获取PreparedStatement，执行SQL
            String sql = "insert into t_user(username,password,age) values (?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setInt(3, user.getAge());
            int num = ps.executeUpdate(); // 受影响的行数
            System.out.println(num);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }finally {
            // 4.关闭资源
            try {
                if(ps != null){
                    ps.close();
                }
                if (conn != null){
                    conn.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }

}
